/**
 * Created by jinxs on 14-7-11.
 * 基于easyui.pagination源码
 */
(function ($) {
    /**
     * 缓存名称
     * @type {string}
     * @private
     */
    var _cacheName = 'uiPagination';
    /**
    * @class 分页组件
    * @constructor uiPagination
    * @summary 构造函数
    * @param [options] {Object|String} 组件配置参数|要调用的组件方法名
    * @param [param] {Object} 表示要调用的组件方法的参数
    * @example
     *  //采用默认值
     * $('#pag').uiPagination();
     * //设置组件参数
     *  $('#pag').uiPagination({total:'1',pageSize:'20'});
     * //调用组件方法
     * $('#pag').uiPagination('refresh',[options]);
    */
    $.fn.uiPagination = function (options, param) {
        if (this.length > 0 && typeof options == "string") {
            return $.fn.uiPagination.methods[options](this.first(), param);
        }
        return this.each(function(){
            var me = $(this);
            var cache = me.data(_cacheName);

            options = options || {};
            if (cache) {
                $.extend(cache.options, options);
            } else {
                me.data(_cacheName, {
                    options: $.extend({}, $.fn.uiPagination.defaults, me.parseUIConfig(), options)
                });
            }
            _init(me);
            _calc(me);
        });
    };
    /**
    * 方法
    * @lends uiAccordion.prototype
    */
    $.fn.uiPagination.methods = {
        /**
        * @summary 获得组件的配置对象
        * @name uiPagination#options
        * @function
        * @returns {Object} 组件的配置对象
        */
        options: function (target) {
            return $.data(target[0], _cacheName).options;
        },
        /**
        * @summary 在组件加载时触发的方法。
        * @event
        * @name uiPagination#loading
        * @this 组件jQuery对象
        * @default function (target)
        */
        loading: function (target) {
            _loadState(target, true);
            return target;
        },
        /**
        * @summary 在组件加载完触发的方法。
        * @event
        * @name uiPagination#loaded
        * @this 组件jQuery对象
        * @default function (target)
        */
        loaded: function (target) {
            _loadState(target, false);
            return target;
        },
        /**
        * @summary 在组件刷新时触发的方法。
        * @event
        * @name uiPagination#refresh
        * @this 组件jQuery对象
        * @default function (target)
        */
        refresh: function (target, options) {
            _calc(target, options);
            return target;
        },
        /**
        * @summary 在选择数据时触发的方法。
        * @event
        * @name uiPagination#refresh
        * @this 组件jQuery对象
        * @default function (target)
        */
        select: function (target, pageIndex) {
            _selectPageEvent(target, pageIndex);
            return target;
        }
    };
    /**
    * 默认配置
    * @lends uiPagination.prototype
    */
    $.fn.uiPagination.defaults = {

        /**
        * @type Number
        * @default 1
        * @summary 指示记录总数
        */
        total: 0,
        /**
        * @type Number
        * @default 20
        * @summary 指示组件的页面大小
        */
        pageSize: 20,
        /**
        * @type Array
        * @default 1
        * @summary 指示组件的起始页
        */
        pageIndex: 1,
        /**
        * @type Array
        * @default [10,20,30，50]
        * @summary 指示组件的页面大小选择项
        */
        pageList: [10, 20, 30, 50],
        /**
        * @type Boolean
        * @default true
        * @summary 指示组件是否加载数据
        */
        loading: false,
        /**
        * @type Boolean
        * @default true
        * @summary 指示组件是否显示页数列表
        */
        showPageList: true,
        /**
        * @type Boolean
        * @default true
        * @summary 指示组件是否显示刷新
        */
        showRefresh: true,
        /**
        * @type String
        * @default ""
        * @summary 指示组件显示的消息
        */
        displayMsg: '',
        /**
        * @type String
        * @default ""
        * @summary 指示组件页数之前显示的文本
        */
        beforePageText: '',
        /**
        * @type String
        * @default ""
        * @summary 指示组件页数之后显示的文本
        */
        afterPageText: '',
        /**
        * @summary 在选择页数时触发的方法。
        * @event
        * @name uiPagination#onSelectPage
        * @this 组件jQuery对象
        * @default emptyFn
        */
        onSelectPage: function (pageIndex, pageSize) {
        },
        /**
        * @summary 在组件刷新之前触发的方法。
        * @event
        * @name uiPagination#onBeforeRefresh
        * @this 组件jQuery对象
        * @default emptyFn
        */
        onBeforeRefresh: function (pageIndex, pageSize) {
        },
        /**
        * @summary 在组件刷新时触发的方法。
        * @event
        * @name uiPagination#onRefresh
        * @this 组件jQuery对象
        * @default emptyFn
        */
        onRefresh: function (pageIndex, pageSize) {
        },
        /**
        * @summary 在页面大小发生变化时触发的方法。
        * @event
        * @name uiPagination#onChangePageSize
        * @this 组件jQuery对象
        * @default emptyFn
        */
        onChangePageSize: function (pageSize) {
        }
    };
    var _init = function (target) {
        var cache = $.data(target[0], _cacheName);
        var options = cache.options;
        target.setElemID().addClass('ui_pagination');
        var targId = target.getElemID();
        var reg=new RegExp('({pageID})','g');
        target.html($($.uiTemplate.pagination.replace(reg, targId)).html());
        var pageInput = $.getByParentID(targId, 'input');
        var sel_pagesize = $.getByParentID(targId, 'pagesize');
        var btnFirst = $.getByParentID(targId, 'first');
        var btnPrev = $.getByParentID(targId, 'prev');
        var btnNext = $.getByParentID(targId, 'next');
        var btnLast = $.getByParentID(targId, 'last');
        var btnLoad = $.getByParentID(targId, 'load');
        var pagination_info = $.getByParentID(targId, 'info');
        var pagination_after = $.getByParentID(targId, 'after');
        sel_pagesize.bind("change", function () {
            options.pageSize = parseInt($(this).val());
            options.onChangePageSize.call(target, options.pageSize);
            //_selectPageEvent(target, options.pageIndex);
        });
        for (var i = 0; i < options.pageList.length; i++) {
            $("<option></option>").text(options.pageList[i]).appendTo(sel_pagesize);
        }

        pageInput.unbind(".pagination").bind("keydown.pagination", function (e) {
            if (e.keyCode == $.keyCode.ENTER) {
                var pageIndex = parseInt($(this).val()) || 1;
                _selectPageEvent(target, pageIndex);
                return false;
            }
        });
        btnFirst.unbind('.pagination').bind('click.pagination', function () {
            if(btnFirst.attr('disabled')){
                return;
            }
            _selectPageEvent(target, 1);
        });
        btnPrev.unbind('.pagination').bind('click.pagination', function () {
            if(btnPrev.attr('disabled')){
                return;
            }
            if (options.pageIndex > 1) {
                _selectPageEvent(target, options.pageIndex - 1);
            }
        });
        btnNext.unbind('.pagination').bind('click.pagination', function () {
            if(btnNext.attr('disabled')){
                return;
            }
            var pageCount = Math.ceil(options.total / options.pageSize);
            if (options.pageIndex < pageCount) {
                _selectPageEvent(target, options.pageIndex + 1);
            }
        });
        btnLast.unbind('.pagination').bind('click.pagination', function () {
            if(btnLast.attr('disabled')){
                return;
            }
            var pageCount = Math.ceil(options.total / options.pageSize);
            if (options.pageIndex < pageCount) {
                _selectPageEvent(target, pageCount);
            }
        });
        btnLoad.unbind('.pagination').bind('click.pagination', function () {
            if (options.onBeforeRefresh.call(this, options.pageIndex, options.pageSize) != false) {
                _selectPageEvent(target, options.pageIndex);
                options.onRefresh.call(target, options.pageIndex, options.pageSize);
            }
        });

        options.displayMsg = pagination_info.html();
        options.afterPageText = pagination_after.html();
    };

    var _selectPageEvent = function (target, pageIndex) {
        var cache = $.data(target[0], _cacheName).options;
        _calc(target, {pageIndex: pageIndex});
        cache.onSelectPage.call(target, cache.pageIndex, cache.pageSize);
    };

    var _calc = function (target, opts) {
        var cache = $.data(target[0], _cacheName);
        var targId=target.getElemID();
        var options = cache.options;
        $.extend(options, opts || {});
        var sel_pagesize = $.getByParentID(targId, 'pagesize');
        if (sel_pagesize.length) {
            sel_pagesize.val(options.pageSize + "");
            options.pageSize = parseInt(sel_pagesize.val());
        }
        var pageindex = Math.ceil(options.total / options.pageSize) || 1;
        if (options.pageIndex < 1) {
            options.pageIndex = 1;
        }
        if (options.pageIndex > pageindex) {
            options.pageIndex = pageindex;
        }
        var pageInput = $.getByParentID(targId, 'input');
        pageInput.val(options.pageIndex);
        var pagination_info = $.getByParentID(targId, 'info');
        var displayMsg = options.displayMsg;
        displayMsg = displayMsg.replace(/{from}/, options.total == 0 ? 0 : options.pageSize * (options.pageIndex - 1) + 1);
        displayMsg = displayMsg.replace(/{to}/, Math.min(options.pageSize * (options.pageIndex), options.total));
        displayMsg = displayMsg.replace(/{total}/, options.total);
        pagination_info.html(displayMsg);

        var pagination_after = $.getByParentID(targId, 'after');
        var pages = options.afterPageText;
        var countPages=Math.ceil(options.total / options.pageSize);
        pages = pages.replace(/{pages}/, countPages==0?1:countPages);
        pagination_after.html(pages);

        var btnFirst = $.getByParentID(targId, 'first');
        var btnPrev = $.getByParentID(targId, 'prev');
        var btnNext = $.getByParentID(targId, 'next');
        var btnLast = $.getByParentID(targId, 'last');
        btnFirst.attr('disabled', (options.pageIndex == 1));
        btnPrev.attr('disabled', (options.pageIndex == 1));
        btnNext.attr('disabled', (options.pageIndex == pageindex));
        btnLast.attr('disabled', (options.pageIndex == pageindex));
        _btnDisabled(btnFirst);
        _btnDisabled(btnPrev);
        _btnDisabled(btnNext);
        _btnDisabled(btnLast);
        _loadState(target, options.loading);
    };
    var _loadState = function (target, loading) {
        var cache = $.data(target[0], _cacheName);
        var options = cache.options;
        options.loading = loading;
        var btnLoad = $.getByParentID(target.getElemID(), 'load');
        if (options.showRefresh && btnLoad) {
            if (options.loading) {
                btnLoad.removeClass('ui_pagination_load').addClass('ui_pagination_loading');
            }
            else {
                btnLoad.removeClass('ui_pagination_loading').addClass('ui_pagination_load');
            }
        }
    };
    var _btnDisabled = function (target) {
        if (target.attr('disabled')) {
            target.addClass('iconDisabled');
        } else {
            target.removeClass('iconDisabled');
        }
    }
})(jQuery);
